#include <iostream>
#include <sys/select.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

//select(int nfd, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout);
//FD_CLR(int fd, fd_set* set);
//FD_SET(int fd, fd_set* set);
//FD_ISSET(int fd, fd_set* set);
//FD_ZERO(fd_set* set);

int main(){
  int fd = open("test.txt", O_RDWR);
  fd_set readfds;
  fd_set writefds;
  FD_ZERO(&readfds);
  FD_ZERO(&writefds);
  FD_SET(0, &readfds);
  FD_SET(fd, &readfds);
  FD_SET(1, &writefds);
  FD_SET(2, &readfds);
  //std::cout << FD_ISSET(5, fds) << std::endl;
  timeval timeout;
  timeout.tv_sec = 0;
  timeout.tv_usec = 0;
  //FD_CLR(fd, fds);
  //close(fd);
  int ret1 = select(fd+1, &readfds, nullptr, nullptr, 0); 
  int ret2 = select(2, nullptr, &writefds, nullptr, &timeout); 
  if(ret1 == -1 || ret2 == -1){
    perror("select");
  }
  else{
    std::cout << "已就绪的读文件描述符: " << ret1 << std::endl;
    std::cout << "已就绪的写文件描述符: " << ret2 << std::endl;
    for(int i = 0; i <= fd; ++i){
      printf("fd[%d] = ", i);
      if(FD_ISSET(i, &readfds)){
        char buf[1024];
        read(i, buf, sizeof(buf));
        std::cout << buf << std::endl;
      }
      else{
        std::cout << "?" << std::endl;
      }
    }
  }
  return 0;
}
